package com.crane.oss.web.support.shiro;


import cn.hutool.core.bean.BeanUtil;
import com.crane.common.core.dto.SessUser;
import com.crane.common.framework.shiro.AbstractUserRealm;
import com.crane.oss.sys.bean.resp.UserBean;
import com.crane.oss.sys.service.UserService;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.Set;


/**
 * 认证
 */
public class UserNamePassWordRealm extends AbstractUserRealm {


    private static final Logger logger = LoggerFactory.getLogger(UserNamePassWordRealm.class);

    @Autowired
    @Lazy
    //延迟Realm实现中Service对象的初始化时间，这样就可以保证Service实际初始化的时候会被BeanPostProcessor拦截，
    //创建具有事务功能的代理对象
    private UserService userService;

    @Override
    protected Set<String> getStringPermissions(PrincipalCollection principals) {
        logger.info("UserNamePassWordRealm doGetAuthorizationInfo");
        SessUser opUser = (SessUser) principals.getPrimaryPrincipal();
        Set<String> permissions = userService.queryAllPerms(opUser);
        return permissions;
    }

    @Override
    protected SessUser getSessUser(AuthenticationToken token) {
        logger.info("UserNamePassWordRealm doGetAuthenticationInfo");
        String username = ((UsernamePasswordToken) token).getUsername();
        String password = new String(((UsernamePasswordToken) token).getPassword());
        String hostName = ((UsernamePasswordToken) token).getHost();
        //查询用户信息
        SessUser user = new SessUser();
        UserBean userBean = userService.userLogin(username, password, hostName);
        if (null != userBean) {
            BeanUtil.copyProperties(userBean, user);
        }
        return user;
    }
}
